<template>
	<view class="order-list" :class="themeName">
		<!-- Tabs -->
		<navbar title="团购订单"></navbar>

		<view class="u-border-bottom" style="background-color: #fff;">
			<view class="flex row-between p-20">
				<view class="act-info flex col--center">{{$zhTran('活动')}}：<text class="act-name">{{actName}}</text>
				</view>
				<view class="rechange-btn" @click="exchangeAct">{{$zhTran('活动切换')}}</view>
			</view>
			<!-- 搜索 -->
			<view class="search-input">
				<u-search class="flex-1" v-model="keyword" height="72" bg-color="#F4F4F4" :show-action="false"
					:placeholder="$zhTran('请输入自提人姓名或手机号')" @search="handleSearch" />
				<view class="search-action" @tap="handleSearch(keyword)">{{$zhTran(' 搜索 ')}}</view>
			</view>
		</view>

		<u-tabs :list="tabsList" :is-scroll="false" :height="80" :active-color="themeColor" :bar-style="{top: '100%'}"
			:current="tabsIndex" @change="changeCurrentTab" />

		<!-- Order Lists -->
		<view class="order-item">
			<mescroll-uni ref="mescrollRef" :fixed="false" :up="{
				  auto: false,
				  noMoreSize: 3,
				  empty: {
				  	icon: $getImageUri('resource/image/shopapi/uniapp/empty/order.png'),
				  	tip: $zhTran('暂无订单~'),
				  	fixed: true
				  }
			  }" :down="{ auto: false }" @init="mescrollInit" @down="downCallback" @up="upCallback">
				<block v-for="(tabItem, tabIndex) in tabsList" :key="tabItem['sign']">
					<view class="order-contain" v-if="currentTab['sign'] === tabItem['sign']">
						<view class="order" v-for="orderItem in tabsList[tabIndex].list" :key="orderItem.id">
							<!-- Order Header -->
							<view class="order-header">
								<view class="flex">
									<view class="avatar flex row-between col-center m-r-20">
										<image :src="orderItem.user.avatar" mode="widthFix" style="width: 50rpx;">
										</image>
									</view>
									<view>
										<view class="name">{{orderItem.user.nickname}}</view>
										<view class="phone">{{$zhTran('手机号')}}: {{orderItem.user.mobile}}</view>
									</view>
								</view>
								<view :class="[
											'order-status', 
											`order-status--${orderStatus[orderItem.order_status]['style']}`
										]">{{ orderStatus[orderItem.order_status]['name'] }}</view>
							</view>

							<!-- Order Main -->
							<view class="order-main m-t-20 p-b-20" @tap="goOrderDetail(orderItem.id)">
								<block v-if="orderItem.order_goods.length > 1">
									<view class="goods-main">
										<block v-for="(goodsItem, goodsIndex) in orderItem.order_goods"
											:key="goodsIndex">
											<image :src="goodsItem.goods_image" mode="widthFix" class="goods-image"
												v-if="goodsIndex < 4">
											</image>
										</block>
										<view class="more-btn" v-if="orderItem.order_goods.length > 3">
											{{$zhTran('共'+orderItem.order_goods.length+'件')}}
										</view>
									</view>
								</block>
								<block v-else>
									<goods-card v-for="(goodsItem, goodsIndex) in orderItem.order_goods"
										:key="goodsIndex" shape="rectangle" :name="goodsItem.goods_name"
										:image="goodsItem.goods_image"
										:contain-style="{ 'border-raius': 0, 'height': '100rpx' }" :fieldShowHide="{
										show_cgp_tag:0
									}" :image-style="{ 'width': '180rpx', 'height': '180rpx' }">
										<view class="flex-1 flex col-bottom" slot="default">
											<text class="lighter sm">x{{ goodsItem.goods_num }}</text>
										</view>
									</goods-card>
								</block>
								<view class="m-t-20">
									<text>{{$zhTran('实付金额')}}：</text>
									<price class="normal lg" :content="orderItem.order_amount" :prefix="price_symbol"
										color="rgba(250, 64, 52, 1)" />
									<text class="m-l-20">{{$zhTran('成交预估收入')}}：</text>
									<price class="normal lg" :content="orderItem.order_profit" :prefix="price_symbol"
										color="rgba(250, 64, 52, 1)" />
								</view>
							</view>

							<!-- Order Footer -->
							<view class="order-footer" v-if="orderItem.buttons.length">
								<block v-for="buttonItem in orderItem.buttons" :key="buttonItem.event">
									<view :class="[
										'order-button', 
										`order-button--${buttonItem.style}`
										]" @tap="onLeaderOrderButtons(buttonItem['event'], orderItem)">{{ buttonItem.name }}</view>
								</block>
							</view>
						</view>
					</view>
				</block>
			</mescroll-uni>

			<u-popup v-model="verificationCodeShow" mode="center" width="80%">
				<view class="verification-code">
					<view class="title flex col--center row-center">{{$zhTran('请输入订单核销码')}}</view>
					<view class="text">
						<u-input :placeholder="$zhTran('请输入11位核销码')" border :value="verification_code"
							@input="inputVerificationCode"></u-input>
					</view>
					<view class="flex btns">
						<view class="confirm p-20" @click="verificationOrder(verification_code,3)">{{$zhTran('确定')}}
						</view>
						<view class="cancel p-20" @click="cancel">{{$zhTran('取消')}}</view>
					</view>
				</view>
			</u-popup>
		</view>
		<u-action-sheet-circle :list="list" :tips="tips" v-model="verificationShow" @click="actionSheet">
		</u-action-sheet-circle>
	</view>
</template>


<script>
	import {
		apiCommunityGroupPurchaseLeaderVerification,
		apiCommunityGroupPurchaseLeaderOrderList
	} from '@/api/community_group_purchase'
	import OrderMixin from '@/mixins/community_group_purchase_order'
	import {
		PaymentStatusEnum
	} from '@/utils/enum'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
	export default {
		name: 'CGPOrderList',
		mixins: [OrderMixin, MescrollMixin],

		data() {
			return {
				// Tabs列表
				tabsList: [{
					sign: 'all',
					name: this.$zhTran('全部'),
					list: [],
				}, {
					sign: 'pay',
					name: this.$zhTran('待付款'),
					list: [],
				}, {
					sign: 'delivery',
					name: this.$zhTran('待发货'),
					list: [],
				}, {
					sign: 'verification',
					name: this.$zhTran('待核销'),
					list: [],
				}, {
					sign: 'finish',
					name: this.$zhTran('已完成'),
					list: [],
				}, {
					sign: 'close',
					name: this.$zhTran('已关闭'),
					list: [],
				}],
				tabsIndex: '', // Tabs索引

				// 订单状态
				orderStatus: {
					0: {
						name: this.$zhTran('待付款'),
						style: 'primary',
					},
					1: {
						name: this.$zhTran('待发货'),
						style: 'primary',
					},
					2: {
						name: this.$zhTran('待核销'),
						style: 'primary',
					},
					3: {
						name: this.$zhTran('已完成'),
						style: 'muted',
					},
					4: {
						name: this.$zhTran('已关闭'),
						style: 'muted',
					}
				},
				keyword: '',
				price_symbol: '￥',
				verification_code: '',
				verificationCodeShow: false,
				tips: {
					text: this.$zhTran('请选择订单核销方式'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
				},
				list: [{
					text: this.$zhTran('直接核销'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'checkmark-circle',
					iconColor: '#fff',
					iconSize: 32,
					iconBgColor: 'rgba(255, 141, 26, 1)',
					iconBgSize: 64,
					iconCircleColor: '#fff6ed',
					iconCircleSize: 138,
				}, {
					text: this.$zhTran('扫码核销'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'scan',
					iconSize: 32,
					iconColor: '#fff',
					iconBgColor: 'rgba(64, 115, 250, 1)',
					iconBgSize: 64,
					iconCircleColor: '#f2f6ff',
					iconCircleSize: 138,
				}, {
					text: this.$zhTran('输入核销码'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'edit-pen',
					iconSize: 32,
					iconColor: '#fff',
					iconBgColor: 'rgba(51, 175, 41, 1)',
					iconBgSize: 64,
					iconCircleColor: '#eff9ee',
					iconCircleSize: 138,
				}],
				verificationShow: false,
				pickup_code: '',
				cgp_id: '',
				actName: '',
			}
		},

		computed: {
			// 当前Tab项
			currentTab() {
				return this.tabsList[this.tabsIndex] || {}
			},

			// 映射Tabs项
			mapTabsItem() {
				return sign => this.tabsList.find(item => item['sign'] === sign)
			}
		},

		methods: {
			// 更改当前Tab页
			changeCurrentTab(index) {
				this.tabsIndex = index
				this.refreshOrderData()
			},

			// 刷新订单数据 @Mixins【/src/mixins/order.js】内调用，请勿删除
			refreshOrderData() {
				this.$nextTick(() => {
					this.mescroll.resetUpScroll()
				})
			},

			// 搜索
			handleSearch(value) {
				console.log(value)
				this.keyword = value
				this.mescroll && this.mescroll.resetUpScroll();
			},

			// 上拉加载更多
			upCallback({
				num,
				size
			}) {
				const sign = this.currentTab.sign
				apiCommunityGroupPurchaseLeaderOrderList({
					type: sign,
					keyword: this.keyword,
					cgp_id: this.cgp_id,
					page_no: num,
					page_size: size,
				}).then(({
					lists,
					page_size,
					count,
					extend
				}) => {
					const tab = this.mapTabsItem(sign)
					lists.forEach(item => item['buttons'] = this.getLeaderOrderStatusButtons(item.btn) ?? [])
					if (num === 1) tab.list = []
					tab.list = [...tab.list, ...lists]
					tab.list = this.$zhTran(tab.list)
					this.price_symbol = extend.price_symbol
					this.actName = this.$zhTran(extend.act_name)
					this.cgp_id = extend.cgp_id
					this.mescroll.endSuccess(lists.length, count)
				}).catch(err => {
					this.mescroll.endErr()
				})
			},

			// 去订单详情
			goOrderDetail(id) {
				this.$Router.push({
					path: '/bundle2/pages/community_group_purchase/leader/order_detail',
					query: {
						order_id: id
					}
				})
			},
			handleVerificationPickup(code) {
				console.log(code)
				this.pickup_code = code
				this.verificationShow = true
			},
			actionSheet(event) {
				if (event === 0) {
					// 直接核销
					this.verificationOrder(this.pickup_code, 1)
				} else if (event === 1) {
					// 扫码核销
					this.scanCode();
				} else if (event === 2) {
					// 输入核销码
					this.verification_code = ''
					this.verificationCodeShow = true;
				}
			},
			scanCode() {
				var that = this,
					themeColor = this.themeColor
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success(res) {
						that.verificationOrder(res.result, 2)
					},
					fail(res) {
						console.log(res)
						// app.alertModal('调用摄像头失败', 2)
					}
				})
			},
			inputVerificationCode(val) {
				this.verification_code = val
			},
			cancel() {
				this.verificationCodeShow = false
				this.verification_code = ''
			},
			verificationOrder(code, flag) {
				var that = this
				console.log('code', code)
				if (code == '' && flag == 3) {
					this.$toast({
						title: this.$zhTran('请填写核销码')
					})
					return
				}
				uni.showModal({
					content: this.$zhTran('确定核销该订单？'),
					confirmColor: this.themeColor,
					confirmText: this.$zhTran('确定'),
					success(res2) {
						if (res2.confirm) {
							apiCommunityGroupPurchaseLeaderVerification({
								code,
							}).then(() => {
								that.refreshOrderData()
							}).finally(() => {
								that.verificationShow = false
								that.verificationCodeShow = false
							})
						}
					}
				})
			},
			exchangeAct() {
				var that = this
				uni.navigateTo({
					url: "/bundle2/pages/community_group_purchase/leader/exchange_activity",
					events: {
						resetCgpId(res) {
							that.cgp_id = res.cgp_id
							that.refreshOrderData()
						}
					},
				});
			}
		},

		onLoad() {
			const options = this.$Route.query
			const mode = options.mode ?? 'all'
			const tabIndex = this.tabsList.findIndex(item => item['sign'] === mode)

			this.changeCurrentTab(tabIndex)
			setTimeout(() => {}, 0.5 * 1000)

			// 监听全局duringPayment事件
			uni.$on('duringPayment', ({
				result
			}) => {
				if (result === PaymentStatusEnum['SUCCESS']) {
					this.$Router.back()
					setTimeout(() => {
						this.$toast({
							title: this.$zhTran('支付成功')
						})
					}, 0.5 * 1000)
					this.refreshOrderData()
				}
			})
		},
		onUnload() {
			uni.$off('duringPayment')
		},
	}
</script>


<style lang="scss">
	page {
		height: 100%;
		padding: 0;
	}

	.order-list {
		height: 100%;
		display: flex;
		flex-direction: column;

		.order-item {
			flex: 1;
			min-height: 0;
		}
	}

	.act-info {
		color: rgba(128, 128, 128, 1);
		font-size: 24rpx;

		.act-name {
			color: rgba(56, 56, 56, 1);
			font-size: 28rpx;
			font-weight: bold;
		}
	}

	.rechange-btn {
		background-color: rgba(255, 208, 0, 1);
		color: rgba(34, 34, 34, 1);
		font-size: 24rpx;
		padding: 10rpx 30rpx;
		border-radius: 50rpx;
	}

	.search-input {
		display: flex;
		align-items: center;
		height: 100rpx;
		padding: 0 20rpx;

		.search-action {
			width: 100rpx;
			text-align: center;
		}
	}

	.order-contain {
		padding: 0 20rpx;
	}

	.order {
		padding-left: 20rpx;
		margin-top: 20rpx;
		border-radius: 5px;
		background-color: #FFFFFF;

		&-header {
			display: flex;
			height: 80rpx;
			align-items: center;
			padding-right: 20rpx;

			.avatar {
				border-radius: 100%;
				overflow: hidden;
			}

			.name {
				color: rgba(56, 56, 56, 1);
				font-size: 28rpx;
			}

			.phone {
				color: rgba(128, 128, 128, 1);
				font-size: 24rpx;
			}

			.order-sn {
				font-size: $-font-size-nr;
			}

			.order-status {
				margin-left: auto;
				font-size: $-font-size-sm;

				&--primary {
					color: rgba(250, 64, 52, 1);
				}

				&--muted {
					color: $-color-muted;
				}
			}
		}

		&-main {

			.goods-main {
				position: relative;

				.goods-image {
					width: calc((100% - 30rpx) / 4);
					margin-right: 10rpx;
					border-radius: 10rpx;
				}

				.goods-image:nth-child(4) {
					margin-right: 0rpx;
				}

				.more-btn {
					position: absolute;
					top: 25rpx;
					right: 0;
					border-radius: 50rpx 0 0 50rpx;
					background-color: rgba(0, 0, 0, 0.5);
					color: #fff;
					font-size: 26rpx;
					padding: 30rpx 20rpx;
				}
			}
		}

		&-footer {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100rpx;
			padding-right: 20rpx;
			border-top: $-solid-border;

			.order-button {
				box-sizing: border-box;
				padding: 10rpx 30rpx;
				border-radius: 2px;
				font-size: $-font-size-nr;

				&:nth-child(n+2) {
					margin-left: 20rpx;
				}

				&--primary {
					background-color: rgba(255, 208, 0, 1);
					color: rgba(74, 25, 0, 1);
				}

				&--normal {
					border-width: 1px;
					border-style: solid;
					@include border_color() @include font_color()
				}

				&--muted {
					border: $-solid-border;
					color: $-color-lighter;
				}
			}
		}

	}


	.verification-code {
		color: rgba(38, 38, 38, 1);
		border-radius: 10rpx;
		overflow: hidden;
		background-color: #FFFFFF;

		.title {
			font-size: 32rpx;
			font-weight: bold;
			margin: 50rpx 0;
		}

		.text {
			margin: 80rpx 30rpx;
		}

		.btns {
			&>view {
				width: 50%;
				text-align: center;
			}

			.confirm {
				background-color: rgba(255, 208, 0, 1);
			}

			.cancel {
				background-color: rgba(244, 246, 249, 1);
			}
		}
	}
</style>